<?php

declare (strict_types = 1);

namespace app\admin\controller\admin;

use app\admin\controller\Base;
use app\admin\model\admin\Role as RoleModel;
use Exception;
use think\db\exception\DbException;
use think\response\Json;

/**
 * 后台管理员用户角色控制器
 */
class Role extends Base
{
    /**
     * 角色列表
     * @return Json
     * @throws DbException
     */
    public function list(): Json
    {
        $model = new RoleModel;
        $list = $model->getList($this->request->param());
        return $this->returnSuccess(compact('list'));
    }

    /**
     * 添加角色
     * @return Json
     */
    public function add(): Json
    {
        // 新增记录
        $model = new RoleModel;
        if ($model->add($this->postForm())) {
            return $this->returnSuccess('添加成功');
        }
        return $this->returnError($model->getError() ?: '添加失败');
    }

    /**
     * 更新角色
     * @return Json
     */
    public function edit(): Json
    {
        $postData = $this->postData();

        // 角色详情
        $model = RoleModel::detail($postData['roleId']);
        // 更新记录
        if ($model->edit($this->postForm())) {
            return $this->returnSuccess('更新成功');
        }
        return $this->returnError($model->getError() ?: '更新失败');
    }

    /**
     * 删除角色
     * @return Json
     * @throws Exception
     */
    public function deleted(): Json
    {
        $postData = $this->postData();

        // 角色详情
        $model = RoleModel::detail($postData['roleId']);
        if (!$model->remove()) {
            return $this->returnError($model->getError() ?: '删除失败');
        }
        return $this->returnSuccess('删除成功');
    }

}
